// import 'package:auto_size_text/auto_size_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
// import 'package:flutter_reorderable_grid_view/flutter_reorderable_grid_view.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/datas/categroy_item.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/domain/widgets/simple_image_loader.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/theme/font_styles.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/widgets/reorderable_grid_view/flutter_reorderable_grid_view.dart';
import 'package:flutter_syt/widgets/web_detail.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

import '../../routes.all.dart';

@RoutePage(name: "categoryManagerPage")
class CategoryManagerPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return CategoryManagerPageState();
  }
}

class CategoryManagerPageState extends State {
  List<CategoryItem> myList = [];
  List<CategoryItem> allList = [];
  bool isLoading = true;
  bool isManage = false;
  List<int> lockedChildrens = [];

  @override
  void initState() {
    getData();
    super.initState();
  }

  void getData() async {
    // setState(() {
    //   isLoading = true;
    // });
    var mys = await API.shared.common.category(0);
    var alls = await API.shared.common.allCategory();
    var allsName = alls.map((e) => e.name).toSet();
    myList = mys.where((element) => allsName.contains(element.name)).toList();
    allList = alls;
    lockedChildrens = getLockedChildren();
    setState(() {
      isLoading = false;
    });
  }

  List<int> getLockedChildren() {
    if (!isManage) {
      List<int> lists = [];
      for (var i = 0; i < myList.length; i++) {
        lists.add(i);
      }
      return lists;
    } else {
      return [];
    }
  }

  Widget loadWidget() {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            "assets/icons/empty.png",
            width: 80,
            height: 80,
          ),
          Container(
            height: 12,
          ),
          Text(
            S.of(context).loading,
            style:
                TextStyle(color: Colors.black.withOpacity(0.4), fontSize: 14),
          ),
          Container(
            height: 20,
          ),
        ],
      ),
    );
  }

  Widget buildItem(CategoryItem e, bool isAll) {
    var ids = myList.map((e) => e.id).toSet();
    var allContain = isAll && ids.contains(e.id);
    return Container(
      key: isAll ? null : Key(e.id),
      width: 80.w,
      height: 80.w,
      child: GestureDetector(
        onTap: ClickUtils.debounce(() {
          if (isManage) {
            if (isAll) {
              if (!allContain) {
                if (myList.length >= 9) {
                  customShowToast(S.of(context).max_9_select);
                  return;
                }
                myList.add(e);
              }
            } else {
              myList.remove(e);
            }
            setState(() {});
          } else {
            var uri = Uri.parse(e.linkUrl);
            var fullPaths = uri.pathSegments;
            var path = '';
            try {
              path = fullPaths.first;
            } catch (e) {}
            if (path == 'web_detail') {
              var parameters = uri.queryParameters;
              Map<String, String> args = {};
              parameters.forEach((key, value) {
                args[key] = value;
              });
              var url = "${args['url']}";
              if (url.isEmpty || url == 'null') {
                RouteManager.push(context, e.linkUrl);
              } else {
                var web = WebDetailPage(url);
                // 占用是不显示原生的，所以为1的时候不显示
                web.needBar = e.head_occupy == 1;
                Navigator.push(
                    context, MaterialPageRoute(builder: (context) => web));
              }
            } else {
              RouteManager.push(context, e.linkUrl);
            }
          }
        }),
        child: Stack(
          children: [
            Container(
              alignment: Alignment.topCenter,
              child: Column(
                // mainAxisSize: MainAxisSize.min,
                // mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  ImageLoader.loadImage(
                    imageUrl: e.icon,
                    width: 44.w,
                    height: 44.w,
                  ),
                  SizedBox(height: 5),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Flexible(
                        child: Text(
                          e.name,
                          maxLines: 2,
                          textAlign: TextAlign.center,
                          style: FontStyles.headerTextStyle_12.copyWith(
                            color: ThemeColor.colorBlack60,
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            if (isManage && (!isAll || (isAll && !allContain)))
              Positioned(
                child: Image.asset(
                  isAll
                      ? "assets/icons/manage_add.png"
                      : "assets/icons/manage_remove.png",
                  width: 18,
                  height: 18,
                ),
                top: 0,
                right: 10,
              ),
            if (isManage && allContain)
              Positioned.fill(
                child: Container(
                  color: Colors.white60,
                ),
              ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    Widget sectionTitle(String text) {
      return Container(
        padding: EdgeInsets.only(left: 20, top: 20, bottom: 20, right: 4),
        child: Row(
          children: [
            Text(
              text,
              style: TextStyle(
                fontSize: 16,
                color: Colors.black,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      );
    }

    // Widget body;
    // if (isLoading) {
    //   body = Center(
    //     child: loadWidget(),
    //   );
    // } else {
    //   // body = gridCount();
    // Widget gridCount() {
    // List<Widget> children = [];
    // // children.add(sectionTitle(S.of(context).My_services));
    // children.addAll(myList.map((e) {
    //   return buildItem(e, false);
    // }).toList());
    // // children.add(sectionTitle(S.of(context).All_services2));
    // children.addAll(allList.map((e) {
    //   return buildItem(e, false);
    // }).toList());
    //   body = ReorderableGridView(
    //     key: const Key('gridViewavds'),
    //     onReorder: (oldIndex, newIndex) {
    //       setState(() {
    //         final draggedItem = allList[oldIndex];
    //         final collisionItem = allList[newIndex];
    //         allList[newIndex] = draggedItem;
    //         allList[oldIndex] = collisionItem;
    //       });
    //     },
    //     gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
    //         crossAxisCount: 4, mainAxisSpacing: 4, crossAxisSpacing: 8),
    //     padding: EdgeInsets.only(top: 0, left: 10, right: 10),
    //     physics: NeverScrollableScrollPhysics(),
    //     children: children,
    //   );
    // }

    // body = SingleChildScrollView(
    //   child: Column(
    //     children: [
    //       // sectionTitle(S.of(context).My_services),
    //       gridCount(

    //       ),
    //       // sectionTitle(S.of(context).All_services2),
    //       // gridCount(
    //       //   allList.map((e) {
    //       //     return buildItem(e, true);
    //       //   }).toList(),
    //       // ),
    //     ],
    //   ),
    // );
    // }

    return Scaffold(
        appBar: AppBar(
          title: Text(S.of(context).All_services1),
          actions: [
            Container(
              alignment: Alignment.center,
              child: GestureDetector(
                onTap: ClickUtils.debounce(() {
                  if (!UserInfo.me.isLogin) {
                    RouteManager.push(context, RoutMapping.loginByPwd());
                    return;
                  }
                  if (isManage) {
                    loading(() async {
                      await API.shared.common
                          .saveCategory(myList.map((e) => e.id).toList());
                    });
                    UserInfo.justNotify();
                  }
                  setState(() {
                    isManage = !isManage;
                    lockedChildrens = getLockedChildren();
                  });
                }),
                child: Container(
                  width: 70,
                  height: 30,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    color: Color(0xffffce00),
                    borderRadius: BorderRadius.all(Radius.circular(4)),
                  ),
                  child: Text(
                    isManage ? S().Done : S().edit_m,
                    style: TextStyle(
                      fontSize: 16,
                      color: Color(0xff111111),
                    ),
                  ),
                ),
              ),
            ),
            Container(
              width: 10,
            ),
          ],
        ),
        body: isLoading
            ? Center(
                child: loadWidget(),
              )
            : SingleChildScrollView(
                child: Column(
                  children: [
                    Row(
                      children: [
                        sectionTitle(S.of(context).My_services),
                        // longTapDrag
                        Visibility(
                          visible: isManage,
                          child: Text(
                            S.of(context).longTapDrag,
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.black.withOpacity(0.4),
                              // fontWeight: FontWeight.bold,
                            ),
                          ),
                        )
                      ],
                    ),
                    ReorderableGridView(
                        key: const Key('gridView'),
                        onReorder: (oldIndex, newIndex) {
                          setState(() {
                            final draggedItem = myList[oldIndex];
                            final collisionItem = myList[newIndex];
                            myList[newIndex] = draggedItem;
                            myList[oldIndex] = collisionItem;
                          });
                        },
                        lockedChildren: lockedChildrens,
                        gridDelegate:
                            const SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 4,
                                mainAxisSpacing: 8,
                                crossAxisSpacing: 8),
                        padding: EdgeInsets.only(top: 0, left: 10, right: 10),
                        physics: NeverScrollableScrollPhysics(),
                        children: myList.map((e) {
                          return buildItem(e, false);
                        }).toList()),
                    sectionTitle(S.of(context).All_services2),
                    GridView.count(
                      physics: NeverScrollableScrollPhysics(),
                      shrinkWrap: true,
                      childAspectRatio: 1,
                      scrollDirection: Axis.vertical,
                      padding: EdgeInsets.only(left: 10, right: 10),
                      crossAxisCount: 4,
                      mainAxisSpacing: 8,
                      crossAxisSpacing: 8,
                      children: allList.map((e) {
                        return buildItem(e, true);
                      }).toList(),
                      // : (context, index) {
                      //   return buildItem(allList[index], true);
                      // },
                    )
                  ],
                ),
              ));
  }
}
